// 假设这是您的 API 服务文件
import http from '../utils/http';
import axios from 'axios';
import { getCurrentUser } from './auth';

const API_BASE_URL = 'http://localhost:5000/api';
const OSS_BASE_URL = 'http://127.0.0.1:8085'; // OSS服务基础URL

// 导入阿里云OSS客户端
import OSS from 'ali-oss';

// 游记项目接口
export interface TravelItem {
  id: string;
  title: string;
  content: string;
  location: string;
  images: string[];
  video: string | null;
  createdAt: string;
  updatedAt: string;
  status: 'pending' | 'approved' | 'rejected';
  author: {
    id: string;
    nickname: string;
    avatar: string;
  };
}

// STS Token响应接口
interface STSTokenResponse {
  AccessKeyId: string;
  AccessKeySecret: string;
  SecurityToken: string;
  Expiration: string;
}

// 上传文件响应接口
interface UploadFileResponse {
  url: string;
  name: string;
  status: string;
}

// 游记列表响应接口
interface TravelListResponse {
  data: TravelItem[];
  total: number;
  totalPages: number;
  page: number;
  limit: number;
}

// 创建游记响应接口
interface CreateTravelResponse {
  code: number;
  message: string;
  data: {
    id: string;
    images: string[];
    video?: string;
  };
}

// 创建axios实例
const axiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 获取阿里云OSS的STS Token
export const getSTSToken = async (): Promise<STSTokenResponse> => {
  try {
    const response = await axios.get(
      `${OSS_BASE_URL}/api/oss/get_sts_token_for_oss_upload?dateTime=${Date.now()}`
    );
    return response.data;
  } catch (error) {
    console.error('获取STS Token失败:', error);
    throw error;
  }
};

// 上传文件到阿里云OSS
export const uploadFileToOSS = async (file: File): Promise<UploadFileResponse> => {
  try {
    // 获取STS Token
    const credentials = await getSTSToken();

    // 创建OSS客户端
    const client = new OSS({
      bucket: 'wen-xuan', // OSS存储桶名称
      region: 'oss-cn-beijing', // OSS区域
      accessKeyId: credentials.AccessKeyId,
      accessKeySecret: credentials.AccessKeySecret,
      stsToken: credentials.SecurityToken,
    });

    // 生成唯一文件名，避免覆盖
    const fileExt = file.name.split('.').pop();
    const fileName = `travel_${Date.now()}_${Math.floor(Math.random() * 1000)}.${fileExt}`;

    // 上传文件
    const result = await client.put(fileName, file);

    return {
      url: result.url,
      name: fileName,
      status: 'done',
    };
  } catch (error) {
    console.error('上传文件失败:', error);
    throw error;
  }
};

// 获取游记列表
export const getTravelList = async (
  page: number = 1,
  limit: number = 10,
  keyword?: string
): Promise<TravelListResponse> => {
  try {
    const params = new URLSearchParams();
    params.append('page', page.toString());
    params.append('limit', limit.toString());
    params.append('status', 'approved'); // 只获取已审核通过的游记

    if (keyword) {
      params.append('keyword', keyword);
    }
    console.log(params.toString());
    const response = await axios.get(`${API_BASE_URL}/travels`, { params });
    return response.data;
  } catch (error) {
    console.error('获取游记列表失败:', error);
    throw error;
  }
};

// 获取游记详情
export const getTravelDetail = async (id: string): Promise<TravelItem> => {
  const response = await axios.get(`${API_BASE_URL}/travels/${id}`);
  return response.data;
};

// 检查登录状态
export const checkLoginStatus = async (): Promise<boolean> => {
  try {
    const user = await getCurrentUser();
    return !!user; // 如果user存在，则返回true
  } catch (error) {
    console.error('检查登录状态失败:', error);
    return false;
  }
};

// 创建游记
export const createTravel = async (data: any): Promise<CreateTravelResponse> => {
  try {
    const response = await axios.post(`${API_BASE_URL}/travels/create`, data, {
      headers: {
        'Content-Type': 'application/json',
      },
    });
    return response.data;
  } catch (error) {
    console.error('创建游记失败:', error);
    throw error;
  }
};

// 点赞游记
export const likeTravel = async (id: string): Promise<void> => {
  await axios.post(`${API_BASE_URL}/travels/${id}/like`);
};

// 取消点赞
export const unlikeTravel = async (id: string): Promise<void> => {
  await axios.delete(`${API_BASE_URL}/travels/${id}/like`);
};

// 分享游记
export const shareTravel = async (id: string): Promise<void> => {
  await axios.post(`${API_BASE_URL}/travels/${id}/share`);
};

// 提交评论
export const submitComment = async (travelId: string, content: string): Promise<void> => {
  await axios.post(`${API_BASE_URL}/travels/${travelId}/comments`, { content });
};

// 获取评论列表
export const getComments = async (travelId: string): Promise<Comment[]> => {
  const response = await axios.get(`${API_BASE_URL}/travels/${travelId}/comments`);
  return response.data;
};

// 获取我的游记列表
export const getMyTravels = async (userId: string) => {
  try {
    // 这里应当调用后端接口获取当前用户的游记列表
    // 示例：const response = await axiosInstance.get(`/users/${userId}/travels`);

    // 目前使用模拟数据，确保状态值与MyTravelItem类型兼容
    return [
      {
        id: '1',
        title: '我的重庆之旅，探索山城的魅力与美食',
        cover: 'https://picsum.photos/300/200?random=4',
        date: '2023-08-05',
        location: '重庆',
        status: 'approved' as const
      },
      {
        id: '2',
        title: '三亚海滩度假，享受阳光与海浪',
        cover: 'https://picsum.photos/300/200?random=5',
        date: '2023-09-15',
        location: '海南三亚',
        status: 'pending' as const
      },
      {
        id: '3',
        title: '西藏朝圣之旅，感受雪域高原的神秘',
        cover: 'https://picsum.photos/300/200?random=6',
        date: '2023-10-01',
        location: '西藏拉萨',
        status: 'rejected' as const
      },
      {
        id: '4',
        title: '北京故宫一日游，探索古代皇家建筑',
        cover: 'https://picsum.photos/300/200?random=7',
        date: '2023-07-20',
        location: '北京',
        status: 'approved' as const,
        isDeleted: true
      }
    ];
  } catch (error) {
    console.error('获取我的游记列表失败:', error);
    throw error;
  }
};

// 导出API函数
const api = {
  getTravelList,
  getTravelDetail,
  checkLoginStatus,
  createTravel,
  likeTravel,
  unlikeTravel,
  shareTravel,
  submitComment,
  getComments,
  getSTSToken,
  uploadFileToOSS,
  getMyTravels
};

export default api;

// 为了兼容性保留的别名导出
export { getTravelDetail as getTravelById };